#include "userinfodialog.h"
#include "ui_userinfodialog.h"
#include "configmanager.h"
#include <QRandomGenerator>
#include <QSettings>

UserInfoDialog::UserInfoDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::UserInfoDialog)
{
    ui->setupUi(this);

    ConfigManager& cm = ConfigManager::instance();

    this->setFixedHeight(cm.screenHeight);
    this->setFixedWidth(cm.screenWidth * 0.4);

    QLabel* avatar = ui->label_avatar;
    avatar->setFixedSize(this->width(), this->width());
    if(cm.avatarNum == -1){
        cm.avatarNum = QRandomGenerator::global()->bounded(13)+1;
    }
    avatar->setPixmap(QPixmap(QString(":/Sprites/Characters/char_%1.png")
        .arg(cm.avatarNum)).scaled(avatar->width(), avatar->height()));
}

UserInfoDialog::~UserInfoDialog()
{
    delete ui;
}

void UserInfoDialog::on_changeButton_clicked()
{
    ConfigManager& cm = ConfigManager::instance();

    cm.avatarNum = QRandomGenerator::global()->bounded(13)+1;

    QLabel* avatar = ui->label_avatar;
    avatar->setPixmap(QPixmap(QString(":/Sprites/Characters/char_%1.png")
        .arg(cm.avatarNum)).scaled(avatar->width(), avatar->height()));
}


void UserInfoDialog::on_confirmButton_clicked()
{
    ConfigManager& cm = ConfigManager::instance();
    cm.nickName = ui->lineEdit->text();
    // 创建配置文件
    QSettings*  m_IniFile = new QSettings("properties.ini", QSettings::IniFormat);
    //通过setValue函数将键值对放在相对于的节下面
    m_IniFile->setValue(QString("USER") + "/" + "NICK_NAME",  cm.nickName);
    m_IniFile->setValue(QString("USER") + "/" + "AVATAR_NUM",  cm.avatarNum);
    delete m_IniFile;
    this->close();
}

